package com.lz.ovuola.util.concurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 线程池 任务处理类
 * 
 * @author fz
 *
 */
public abstract class ThreadPoolExecutor {

	private static final int cores = Runtime.getRuntime().availableProcessors();

	private static final ExecutorService EXECUTOR_SERVICE = Executors
			.newFixedThreadPool(cores * 4);

	private static Logger logger = LoggerFactory
			.getLogger(ThreadPoolExecutor.class);

	/**
	 * Executes the given command at some time in the future. The command may
	 * execute in a new thread, in a pooled thread, or in the calling thread, at
	 * the discretion of the {@code Executor} implementation.
	 *
	 * @param command
	 *            the runnable task
	 * @throws RejectedExecutionException
	 *             if this task cannot be accepted for execution
	 * @throws NullPointerException
	 *             if command is null
	 */
	public static final void execute(Runnable runnable) {
		EXECUTOR_SERVICE.execute(runnable);
	}

	/**
	 * Submits a value-returning task
	 * 
	 * @param callable
	 * @return
	 */
	public static final <T> Future<T> submit(Callable<T> callable) {
		return EXECUTOR_SERVICE.submit(callable);
	}

	/**
	 * Submits a Runnable task for execution
	 * 
	 * @param runnable
	 */
	public static final Future<?> submit(Runnable runnable) {
		return EXECUTOR_SERVICE.submit(runnable);
	}

	/**
	 * shutdown pool
	 */
	public static final void shutdown() {
		logger.info("准备关闭线程池");
		EXECUTOR_SERVICE.shutdown();
	}

	public static int getCores() {
		return cores;
	}

	// public static void main(String[] args) throws InterruptedException,
	// ExecutionException {
	// Future<String> future = submit(() -> {
	// return "i had received";
	// });
	// System.out.println(future.get());
	// }

}
